package com.cjm.lecode;

/**
 * 题目: 请实现一个函数, 把字符串中的每个空格替换成%20, 例如, 输入"we are happy", 则输出"we%20are%20happy";
 */
public class Demo5 {
    public static void main(String[] args) {
        char[] abc = new char[20];
        String str = "We are happy.";
        char[] chars = str.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            abc[i] = chars[i];
        }

        System.err.println(getstr(abc, 20));
    }

    private static String getstr(char[] str, int size) {
        if (str == null||str.length <= 0) return "";
        int originLength = 0;
        int numberOfBlank = 0;
        int i = 0;
        while (str[i] != '.') {
            originLength++;
            if (str[i] == ' ') {
                numberOfBlank++;
            }
            i++;
        }
        originLength++;

        int newLength = originLength + numberOfBlank * 2;
        if (newLength > size) return "";
        int indexOfOriginal = originLength;
        int indexOfNew = newLength;

        while (indexOfOriginal >=0 && indexOfNew > indexOfOriginal) {
            if (str[indexOfOriginal] == ' ') {
                str[indexOfNew--] = '0';
                str[indexOfNew--] = '2';
                str[indexOfNew--] = '%';
            }else{
                str[indexOfNew--] = str[indexOfOriginal];
            }
            indexOfOriginal--;
        }
        return str.toString();
    }
}
